<template>
  <div class="dispatch-config">
    <el-card class="config-card">
      <div slot="header" class="clearfix">
        <span>配送调度配置</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleAddConfig">
          添加配置
        </el-button>
      </div>
      
      <div v-if="loading" class="loading">
        <el-skeleton :rows="6" animated />
      </div>
      
      <div v-else>
        <el-table :data="configList" border style="width: 100%">
          <el-table-column prop="name" label="配置名称" width="180"></el-table-column>
          <el-table-column prop="algorithmType" label="算法类型" width="180">
            <template slot-scope="scope">
              {{ getAlgorithmName(scope.row.algorithmType) }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
          <el-table-column prop="isActive" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isActive === 1 ? 'success' : 'info'">
                {{ scope.row.isActive === 1 ? '激活' : '未激活' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.isActive !== 1"
                size="mini"
                type="success"
                @click="handleActivate(scope.row)">激活</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)">编辑</el-button>
              <el-button
                v-if="scope.row.isActive !== 1"
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 配置表单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form ref="configForm" :model="configForm" :rules="configRules" label-width="100px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="configForm.name" placeholder="请输入配置名称"></el-input>
        </el-form-item>
        <el-form-item label="算法类型" prop="algorithmType">
          <el-select v-model="configForm.algorithmType" placeholder="请选择算法类型" style="width: 100%">
            <el-option label="随机分配" :value="1"></el-option>
            <el-option label="最近骑手优先" :value="2"></el-option>
            <el-option label="评分最高骑手优先" :value="3"></el-option>
            <el-option label="最少订单骑手优先" :value="4"></el-option>
            <el-option label="综合算法" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          v-if="configForm.algorithmType === 5" 
          label="权重配置" 
          prop="weightConfig"
        >
          <el-form-item label="距离因素" class="weight-item">
            <el-slider v-model="weights.distance" :step="0.1" :min="0" :max="1"></el-slider>
            <span class="weight-value">{{ weights.distance }}</span>
          </el-form-item>
          <el-form-item label="评分因素" class="weight-item">
            <el-slider v-model="weights.rating" :step="0.1" :min="0" :max="1"></el-slider>
            <span class="weight-value">{{ weights.rating }}</span>
          </el-form-item>
          <el-form-item label="订单因素" class="weight-item">
            <el-slider v-model="weights.orders" :step="0.1" :min="0" :max="1"></el-slider>
            <span class="weight-value">{{ weights.orders }}</span>
          </el-form-item>
          <div class="weight-sum">
            权重和: {{ weightSum }} 
            <el-tag :type="weightSum === 1 ? 'success' : 'danger'" size="small">
              {{ weightSum === 1 ? '有效' : '无效' }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch 
            v-model="configForm.isActive" 
            :active-value="1" 
            :inactive-value="0"
            active-text="激活" 
            inactive-text="未激活">
          </el-switch>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="configForm.description" :rows="3" placeholder="请输入配置描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :disabled="configForm.algorithmType === 5 && weightSum !== 1">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getDispatchConfigs, 
  activateDispatchConfig, 
  addDispatchConfig, 
  updateDispatchConfig, 
  deleteDispatchConfig 
} from '@/api/admin'

export default {
  name: 'DispatchConfig',
  data() {
    return {
      configList: [],
      loading: true,
      dialogVisible: false,
      dialogTitle: '添加配置',
      isEdit: false,
      
      configForm: {
        id: null,
        name: '',
        algorithmType: 1,
        weightConfig: '',
        isActive: 0,
        description: ''
      },
      
      weights: {
        distance: 0.5,
        rating: 0.3,
        orders: 0.2
      },
      
      configRules: {
        name: [
          { required: true, message: '请输入配置名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        algorithmType: [
          { required: true, message: '请选择算法类型', trigger: 'change' }
        ],
        description: [
          { max: 200, message: '不超过200个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    weightSum() {
      const sum = this.weights.distance + this.weights.rating + this.weights.orders
      return Math.round(sum * 10) / 10 // 四舍五入到一位小数
    }
  },
  created() {
    this.fetchConfigList()
  },
  methods: {
    fetchConfigList() {
      this.loading = true
      getDispatchConfigs()
        .then(response => {
          this.configList = response.data
        })
        .catch(error => {
          console.error('获取配送配置失败:', error)
          this.$message.error('获取配送配置失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    getAlgorithmName(type) {
      const algorithms = {
        1: '随机分配',
        2: '最近骑手优先',
        3: '评分最高骑手优先',
        4: '最少订单骑手优先',
        5: '综合算法'
      }
      return algorithms[type] || '未知算法'
    },
    
    parseWeightConfig(configStr) {
      try {
        if (configStr) {
          const config = JSON.parse(configStr)
          this.weights = {
            distance: config.distance || 0.5,
            rating: config.rating || 0.3,
            orders: config.orders || 0.2
          }
        }
      } catch (e) {
        console.error('解析权重配置失败:', e)
        // 使用默认值
        this.weights = {
          distance: 0.5,
          rating: 0.3,
          orders: 0.2
        }
      }
    },
    
    prepareWeightConfig() {
      // 仅在综合算法时需要设置权重
      if (this.configForm.algorithmType === 5) {
        this.configForm.weightConfig = JSON.stringify(this.weights)
      } else {
        this.configForm.weightConfig = ''
      }
    },
    
    resetForm() {
      if (this.$refs.configForm) {
        this.$refs.configForm.resetFields()
      }
      
      this.configForm = {
        id: null,
        name: '',
        algorithmType: 1,
        weightConfig: '',
        isActive: 0,
        description: ''
      }
      
      this.weights = {
        distance: 0.5,
        rating: 0.3,
        orders: 0.2
      }
    },
    
    handleAddConfig() {
      this.dialogTitle = '添加配置'
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },
    
    handleEdit(row) {
      this.dialogTitle = '编辑配置'
      this.isEdit = true
      this.resetForm()
      
      // 复制数据到表单
      this.configForm = { ...row }
      
      // 解析权重配置
      if (row.algorithmType === 5) {
        this.parseWeightConfig(row.weightConfig)
      }
      
      this.dialogVisible = true
    },
    
    handleActivate(row) {
      this.$confirm('确定要激活该配置吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        activateDispatchConfig(row.id)
          .then(() => {
            this.$message.success('激活成功')
            this.fetchConfigList()
          })
          .catch(error => {
            console.error('激活配置失败:', error)
            this.$message.error('激活配置失败')
          })
      }).catch(() => {
        // 取消激活
      })
    },
    
    handleDelete(row) {
      this.$confirm('确定要删除该配置吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDispatchConfig(row.id)
          .then(() => {
            this.$message.success('删除成功')
            this.fetchConfigList()
          })
          .catch(error => {
            console.error('删除配置失败:', error)
            this.$message.error('删除配置失败')
          })
      }).catch(() => {
        // 取消删除
      })
    },
    
    submitForm() {
      this.$refs.configForm.validate(valid => {
        if (valid) {
          // 准备权重配置
          this.prepareWeightConfig()
          
          const request = this.isEdit 
            ? updateDispatchConfig(this.configForm)
            : addDispatchConfig(this.configForm)
            
          request
            .then(() => {
              this.$message.success(this.isEdit ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchConfigList()
            })
            .catch(error => {
              console.error(this.isEdit ? '更新配置失败:' : '添加配置失败:', error)
              this.$message.error(this.isEdit ? '更新配置失败' : '添加配置失败')
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.dispatch-config {
  padding: 20px;
}

.config-card {
  margin-bottom: 20px;
}

.loading {
  padding: 20px;
}

.weight-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.weight-item .el-form-item__label {
  width: 70px !important;
}

.weight-item .el-slider {
  margin-left: 10px;
  width: 300px;
}

.weight-value {
  display: inline-block;
  width: 40px;
  text-align: center;
  margin-left: 10px;
}

.weight-sum {
  margin-top: 15px;
  text-align: right;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style> 